<?php
require_once(APPLICATION_PATH . '/../library/tcpdf/tcpdf_include.php');

class CustomerController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_customer');
        $this->session_search_key = 'controller_customer';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'customer', '');
    }

    public function viewAction() {

        if ($this->_getParam('cust_id') && $this->_getParam('cust_id') != "") {
            $cust_id = $this->_getParam('cust_id');
        } else {
            $this->_helper->redirector('list', 'customer', '');
        }
        $customerModel = new Model_Customer();

        $customerdata = $customerModel->fetchEntryByViewId($cust_id,$this->USER->usr_lang_id);

        $updated_id = $customerdata['lgn_id'];
        $login_type = $customerdata['lgn_type'];

        //Load login model
        $loginModel = new Model_Login();
        //$updated_admin_Data=$loginModel->updateddataname($login_type,$updated_id);

        /** get user name which is updated data * */
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        
        //load model departmentcontractor
        $departmentcustomerModel = new Model_Departmentcustomer();
        $departmentdata = $departmentcustomerModel->fetchDepartmentByCustomer($cust_id);
        
       /* foreach ($departmentdata as $key =>$value){
            $departmentname = $customerModel->getdepartmentArray("dep_id = '".$value."'"); 
        }*/
        $departmentModel = new Model_Department();
        foreach ($departmentdata as $key =>$value){
            $departmentDetail[] = $departmentModel->fetchDepartment("dep_id = '".$value."'"); 
        }
        foreach ($departmentDetail as $dkey =>$dvalue){
            $departmentname[] = $dvalue[0]['dep_name']; 
        }
        
        
        $this->view->admindata = $user_name;
        $this->view->departmentName = implode(",",$departmentname);
        $this->view->customerdata = $customerdata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "1 = 1";
        $searchtype = "";
        $orderField = 'cust_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }
        /* Pagination Login */
        $metaDataModel = new Model_Metadata();
        /* Admin page record * */
        $ADMIN_PAGE_RECORD = $metaDataModel->fetchEntryByKey("PAGE_RECORD");
        $ADMIN_RECORD = $ADMIN_PAGE_RECORD['mtd_value'];

        if ($ADMIN_RECORD != '') {
            $itemsPerPageReviews = $ADMIN_RECORD;
        } else {
            $itemsPerPageReviews = $this->config->PAGING_PER_PAGE;
        }
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }

            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "cust_firstname LIKE '%$searchtype%' OR lgn_email LIKE '%$searchtype%' OR com_name LIKE '%$searchtype%'
                          OR CONCAT(cust_firstname , ' ', cust_lastname)= '$searchtype'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = $searchtype;
                $this->view->searchtype = $searchtype;
            }
        } else {
            
            if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = '';
            }$searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'];
            $where = "cust_firstname LIKE '%$searchtype%' OR lgn_email LIKE '%$searchtype%' OR com_name LIKE '%$searchtype%'
                      OR CONCAT(cust_firstname , ' ', cust_lastname)= '$searchtype'";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'];
        }
        /** if logged user is customer then list only those customer which are same company
         *  logged customer company =all customer company * *
         * * */
        $login_role = $this->USER->role;
        if ($login_role == 'CUSTOMER'):
            $login_companyid = $this->USER->company_id;
            $where .=') AND ( cust.com_id=' . $login_companyid;
        else:
            $where .="";
        endif;
        
         if ($this->_getParam('com_id') && $this->_getParam('com_id') != "" ){
            $where .= ")AND (cust.com_id = '".$this->_getParam('com_id')."'";
         }
         
        // customer model
        $customerModel = new Model_Customer();
        $customersData = $customerModel->fetchCustomer($this->USER->usr_lang_id,$where, $itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($customerModel->getCustomerCount($this->USER->usr_lang_id,$where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'customer', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->customersData = $customersData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $customerModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Customer Model 
        $customerModel = new Model_Customer();

        if ($this->_getParam('cust_id') && $this->_getParam('cust_id') != "") {
            $cust_id = $this->_getParam('cust_id');
            $customerdata = $customerModel->fetchEntryById($cust_id);
            $company_id = $customerdata['com_id'];
            /* if logged user is customer and
             * customer's company  and logged customer's company not same then redirect to list page */
            if ($this->USER->role == 'CUSTOMER') {
                //check both company same or not
                if ($company_id == $this->USER->company_id) {
                    $customerModel->deleteCustomer($cust_id);
                    $this->addSuccessMessage($this->ZFTRANSLATE->translate("customer_delete_success"));
                }
            } else {
                $customerModel->deleteCustomer($cust_id);
                $this->addSuccessMessage($this->ZFTRANSLATE->translate("customer_delete_success"));
            }
            $this->_helper->redirector('list', 'customer', '');
        } else {
            $customerModel->deleteCustomer($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("customer_delete_success"));
            $this->_helper->redirector('list', 'customer', '');
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $customerData = Array();
        $this->view->mode = "Add";
        $where = "";
        $cust_issupercontractor = "";
        //Load login Model
        $loginModel = new Model_Login();
        
        $departmentcustomerModel = new Model_Departmentcustomer(); // load department contractor model

        //Load Customer Model
        $customerModel = new Model_Customer();

        //Load Customer Form
        $customerForm = new Form_CustomerForm();

        $imageName = "";
        $customer_com_id = "";
        //Load the country array for the select box in form 
        $countryArray = $customerModel->getcountryArray();
        $customerForm->cust_country->addMultiOptions($countryArray);


        //Load the quality array for the select box in form 
        $qualityArray = $customerModel->getqualityArray($this->USER->usr_lang_id);
        $customerForm->cust_quality->addMultiOptions($qualityArray);

        //Load the title  array for the select box in form 
        $titleArray = $customerModel->gettitleArray($this->USER->usr_lang_id);
        $customerForm->cust_title->addMultiOptions($titleArray);
        
        
        //Load the availability array for the select box in form 
        $availabilityArray = $customerModel->getavailabilityArray($this->USER->usr_lang_id);
        $customerForm->cust_availability->addMultiOptions($availabilityArray);


        //Load the country array for the select box in form 
        $companyArray = $customerModel->getcompanyArray("com_type = 2");
        $customerForm->com_id->addMultiOptions($companyArray);

        
       
        
        
        //Load the status array for the select box in form 
        $statusArray = $customerModel->getStatusArray();
        $customerForm->cust_status->addMultiOptions($statusArray);

        //Load the language array for the select box in form 
        $languageArray = $customerModel->getlanguageArray();
        $customerForm->lang_id->addMultiOptions($languageArray);


        //Check for the customer Parameter
        $customerData['cust_id'] = $this->_request->getParam('cust_id');
        $cust_id = (!empty($customerData['cust_id'])) ? $customerData['cust_id'] : null;

        if (!empty($cust_id)) {
            $customerForm->lgn_email->setAttribs(Array('readonly' => true));
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $customerModel->fetchEntryById($cust_id);
            $lgn_id = $data['lgn_id'];
            $customer_com_id = $data['com_id'];
            $currentEmail = $data['lgn_email'];
            $imageName = $data['cust_image'];
            //  $data['lgn_email_update'] = $data['lgn_email'];
            $data['cust_status'] = $data['lgn_active'];
            
             //Department data
            $departmentcustomerData = $departmentcustomerModel ->fetchDepartmentByCustomer($cust_id);
            $data['dep_id'] = $departmentcustomerData;
            
            $where = "site.com_id = '".$customer_com_id."'";
            $cust_issupercontractor = $data['cust_isadmin'];
            
        }
        
          //Load the department array for the select box in form 
        $departmentArray = $customerModel->getdepartmentArray($where);
        $customerForm->dep_id->addMultiOptions($departmentArray);
        
        //Populate form 
        $this->view->form = $customerForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();
            
            if($postedData['com_id'] != ""){
                $departmentArray = $customerModel->getdepartmentArray("site.com_id = '".$postedData['com_id']."'");
                $customerForm->dep_id->addMultiOptions($departmentArray);
            }
        
            if (!$customerForm->isValid($postedData)) {
                $errorMessage = $customerForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {

                //Image Validation
                if ($_FILES['cust_image']['name'] != '') {
                    $gtlObj = new GTL_Common();
                    $imageAllowedFormat = $gtlObj->allowedImageFormats();
                    $responseText = $gtlObj->image_validate($imageAllowedFormat, 'cust_image');
                    if ($responseText == 'IMPROPER_FORMAT') {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_image");
                    }
                }
                if ($this->view->mode == "Add") {
                    //Check for the email exist while Adding custoemr
                    $customerExist = $loginModel->checkEmailExist($postedData['lgn_email']);
                    if ($customerExist) {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("email_check");
                    }
                    //Password Validation
                    if ($postedData['lgn_password'] == "") {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_password");
                    }
                    if ($postedData['lgn_password'] != "") {

                        if ($postedData['lgn_confirmpassword'] == "") {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_conf_password");
                            ;
                        }

                        if ($postedData['lgn_password'] != $postedData['lgn_confirmpassword']) {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_match_password");
                        }
                    }
                }

                if (count($errorMessageArray) > 0) {
                    
                } else {
                    //Image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "customer/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);

                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $customerData['cust_image'] = $fileName;
                        }
                    }
                    
                    if ($this->view->mode == "Add") {
                        $CustomerCount = $customerModel->getCustomerCount($this->USER->usr_lang_id,'cust_isadmin=1');
                        # echo  $CustomerCount;exit;
                        if ($CustomerCount == 0) {
                            $customerData['cust_isadmin'] = 1;
                        }
                        $customerData['cust_createddate'] = date("Y-m-d H:i:s");
                        $password = ($postedData['lgn_password'] == "") ? "" : md5($postedData['lgn_password']);
                        $loginData['lgn_email'] = $postedData['lgn_email'];
                        $loginData['lgn_password'] = $password;
                        $loginData['lgn_type'] = '3';
                        $loginData['lgn_created'] = date("Y-m-d H:i:s");
                        $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                        $loginData['lgn_active'] = $postedData['cust_status']; //$postedData['lgn_active'];
                        $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        
                    } else {
                        if ($postedData['lgn_password'] != "") {
                            $password = md5($postedData['lgn_password']);
                            $loginData['lgn_email'] = $postedData['lgn_email'];
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_password'] = $password;
                            $loginData['lgn_type'] = '3';
                            $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                            $loginData['lgn_active'] = $postedData['cust_status']; //$postedData['lgn_active'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        } else {
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_active'] = $postedData['cust_status'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        }
                    }
                    /*                     * authentication login id */
                    $updated_userid = $this->USER->lgn_id;
                    //Customer save
                    $customerData['updated_lgn_id'] = $updated_userid;
                    $customerData['cust_id'] = $cust_id;
                    $customerData['lgn_id'] = $lgn_id;
                    $customerData['lang_id'] = $postedData['lang_id'];
                    $customerData['com_id'] = $postedData['com_id'];
                    $customerData['cust_title'] = $postedData['cust_title'];
                    $customerData['cust_firstname'] = $postedData['cust_firstname'];
                    $customerData['cust_lastname'] = $postedData['cust_lastname'];
                    $customerData['cust_phone'] = $postedData['cust_phone'];
                    $customerData['cust_mobile_no'] = $postedData['cust_mobile_no'];
                    $customerData['cust_fax'] = $postedData['cust_fax'];
                    $customerData['cust_address'] = $postedData['cust_address'];
                    $customerData['cust_city'] = $postedData['cust_city'];
                    $customerData['cust_state'] = $postedData['cust_state'];
                    $customerData['cust_country'] = $postedData['cust_country'];
                    $customerData['cust_zipcode'] = $postedData['cust_zipcode'];
                    $customerData['cust_quality'] = $postedData['cust_quality'];
                    $customerData['cust_securityquestion'] = $postedData['cust_securityquestion'];
                    $customerData['cust_securityanswer'] = $postedData['cust_securityanswer'];
                    $customerData['cust_availability'] = $postedData['cust_availability'];
                    $customerData['cust_updateddate'] = date("Y-m-d H:i:s");

                    $Customerid =  $customerModel->save($customerData, 'cust_id');
                    
                   
                    $department_customer['cust_id'] = $Customerid;
                    $department_customer['lgn_id'] = $lgn_id;
                    $department_customer['cust_dep_status'] = $postedData['cust_status'];
                    $department_customer['updated_lgn_id'] = $updated_userid;
                    $department_customer['cust_dep_createddate'] = date("Y-m-d H:i:s");
                    
                    //delete all department of customer
                    $departmentcustomerData = $departmentcustomerModel ->fetchDepartmentBycustomer($Customerid);
                    
                    foreach ($departmentcustomerData as $key => $_depp){
                         $departmentcustomerModel->deleteDepartmentcustomer($key);
                    }
                     
                    foreach ($postedData['dep_id'] as $value){
                        $department_customer['dep_id'] = $value;
                        $departmentcustomerModel->save($department_customer, 'con_dep_id');
                    }
                    
                    
                    
                    
                    
                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("customer_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("customer_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'customer', '');
                }
            }
        }

         /**         * *  
         * if contractor is supercontractor then redirect to list page
         * * * */
        if ($cust_issupercontractor == 1) {
            $this->_helper->redirector('list', 'customer', '');
        }
        
        /* if logged user is customer and
         * *  customer's company  and logged customer's company not same then redirect to list page */


        if (($customer_com_id != $this->USER->company_id) && $this->USER->role == 'CUSTOMER' && $cust_id != '') {
            $this->_helper->redirector('list', 'customer', '');
        } else {

            /** login user role and company id* */
            $this->view->mode = $this->view->mode;
            $this->view->login_user_role = $this->USER->role;
            $this->view->login_user_company = $this->USER->company_id;
            $this->view->customer_company_id = $customer_com_id;

            $this->view->customerid = $cust_id;
            $this->view->imageName = $imageName;
            $this->view->errorMessageArray = $errorMessageArray;
            $this->view->succesMessage = $successmessage;
            $this->view->form = $customerForm;
        }
    }

    public function editprofileAction() {
        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $customerData = Array();
        $this->view->mode = "Add";
        //Load login Model
        $loginModel = new Model_Login();
        $departmentcustomerModel = new Model_Departmentcustomer(); // load department contractor model
         
        //Load Customer Model
        $customerModel = new Model_Customer();
        //Load Customer Form
        $customerForm = new Form_CustomerForm();
        $imageName = "";
        //Load the country array for the select box in form 
        $countryArray = $customerModel->getcountryArray();
        $customerForm->cust_country->addMultiOptions($countryArray);
        //Load the quality array for the select box in form 
        $titleArray = $customerModel->gettitleArray($this->USER->usr_lang_id);
        $customerForm->cust_title->addMultiOptions($titleArray);
        
        
        //Load the quality array for the select box in form 
        $qualityArray = $customerModel->getqualityArray($this->USER->usr_lang_id);
        $customerForm->cust_quality->addMultiOptions($qualityArray);
        
        
        //Load the availability array for the select box in form 
        $availabilityArray = $customerModel->getavailabilityArray($this->USER->usr_lang_id);
        $customerForm->cust_availability->addMultiOptions($availabilityArray);


        //Load the country array for the select box in form 
        $companyArray = $customerModel->getcompanyArray("com_type = 2");
        $customerForm->com_id->addMultiOptions($companyArray);

        //Load the status array for the select box in form 
        $statusArray = $customerModel->getStatusArray();
        $customerForm->cust_status->addMultiOptions($statusArray);

        //Load the language array for the select box in form 
        $languageArray = $customerModel->getlanguageArray();
        $customerForm->lang_id->addMultiOptions($languageArray);


        if ($this->USER->role == 'CUSTOMER') {
            //Check for the customer Parameter
            //get contarctor id from login id
            $admin_id_model = $customerModel->getadminId($this->view->user->lgn_id);
            $customerData['cust_id'] = $admin_id_model['cust_id'];
            // $customerData['cust_id'] = $this->_request->getParam('cust_id');
            $cust_id = (!empty($customerData['cust_id'])) ? $customerData['cust_id'] : null;
        } else {
            $cust_id = "";
        }
        if (!empty($cust_id)) {
            $customerForm->lgn_email->setAttribs(Array('readonly' => true));
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $customerModel->fetchEntryById($cust_id);
            $lgn_id = $data['lgn_id'];
            $currentEmail = $data['lgn_email'];
            $imageName = $data['cust_image'];
            //$data['lgn_email_update'] = $data['lgn_email'];
            $data['cust_status'] = $data['lgn_active'];
            $customer_com_id = $data['com_id'];
            //Department data
            $departmentcustomerData = $departmentcustomerModel ->fetchDepartmentByCustomer($cust_id);
            $data['dep_id'] = $departmentcustomerData;
            
            $where = "site.com_id = '".$customer_com_id."'";
         
        
        }
         //Load the department array for the select box in form 
        $departmentArray = $customerModel->getdepartmentArray($where);
        $customerForm->dep_id->addMultiOptions($departmentArray);
        //Populate form 
        $this->view->form = $customerForm->populate($data);
        if ($this->getRequest()->isPost()) {
            //Check for Errors
            $postedData = $this->_request->getPost();

            if($postedData['com_id'] != ""){
                $departmentArray = $customerModel->getdepartmentArray("site.com_id = '".$postedData['com_id']."'");
                $customerForm->dep_id->addMultiOptions($departmentArray);
            }
            
            if (!$customerForm->isValid($postedData)) {
                $errorMessage = $customerForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {

                //Image Validation
                if ($_FILES['cust_image']['name'] != '') {
                    $gtlObj = new GTL_Common();
                    $imageAllowedFormat = $gtlObj->allowedImageFormats();
                    $responseText = $gtlObj->image_validate($imageAllowedFormat, 'cust_image');
                    if ($responseText == 'IMPROPER_FORMAT') {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_image"); #'Please upload image with valid file format.';
                    }
                }

                if ($this->view->mode == "Add") {
                    //Check for the email exist while Adding custoemr
                    $customerExist = $loginModel->checkEmailExist($postedData['lgn_email']);
                    if ($customerExist) {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("email_check");
                    }
                    //Password Validation
                    if ($postedData['lgn_password'] == "") {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_password");
                    }
                    if ($postedData['lgn_password'] != "") {

                        if ($postedData['lgn_confirmpassword'] == "") {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_conf_password");
                        }

                        if ($postedData['lgn_password'] != $postedData['lgn_confirmpassword']) {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("customer_required_match_password");
                        }
                    }
                }

                if (count($errorMessageArray) > 0) {
                    
                } else {
                    //Image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "customer/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $customerData['cust_image'] = $fileName;
                        }
                    }
                    if ($this->view->mode == "Add") {
                        $CustomerCount = $customerModel->getCustomerCount('');
                        if ($CustomerCount == 0) {
                            $customerData['cust_isadmin'] = 1;
                        }
                        $customerData['cust_createddate'] = date("Y-m-d H:i:s");
                        $password = ($postedData['lgn_password'] == "") ? "" : md5($postedData['lgn_password']);
                        $loginData['lgn_email'] = $postedData['lgn_email'];
                        $loginData['lgn_password'] = $password;
                        $loginData['lgn_type'] = '3';
                        $loginData['lgn_created'] = date("Y-m-d H:i:s");
                        $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                        $loginData['lgn_active'] = $postedData['cust_status']; //$postedData['lgn_active'];
                        $lgn_id = $loginModel->save($loginData, 'lgn_id');
                    } else {
                        if ($postedData['lgn_password'] != "") {
                            $password = md5($postedData['lgn_password']);
                            $loginData['lgn_email'] = $postedData['lgn_email'];
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_password'] = $password;
                            $loginData['lgn_type'] = '3';
                            $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                            $loginData['lgn_active'] = $postedData['cust_status']; //$postedData['lgn_active'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        } else {
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_active'] = $postedData['cust_status'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        }
                    }

                    /** authentication login id */
                    $updated_userid = $this->USER->lgn_id;

                    /*                     * ********update language id and code in session************** */
                    $dataUpdate = array();
                    $authData = Zend_Auth::getInstance()->getIdentity();
                    /* Language code */
                    $languageModel = new Model_Language();
                    $where = 'lang_id=' . $postedData['lang_id'];
                    $languagedefaultArray = $languageModel->fetchType($where);
                    $authData->usr_lang_id = $postedData['lang_id'];
                    $authData->usr_lang_code = strtolower($languagedefaultArray[0]['lang_code']);
                    $authData->language = strtolower($languagedefaultArray[0]['lang_code']);
                    $dataUpdate['usr_lang_id'] = $postedData['lang_id'];
                    $dataUpdate['usr_lang_code'] = strtolower($languagedefaultArray[0]['lang_code']);
                    $dataUpdate['language'] = strtolower($languagedefaultArray[0]['lang_code']);
                    // $customerModel->save($dataUpdate, 'lgn_id');
                    /*                     * *********************************************************** */

                    //Customer save
                    $customerData['updated_lgn_id'] = $updated_userid;
                    $customerData['cust_id'] = $cust_id;
                    $customerData['lgn_id'] = $lgn_id;
                    $customerData['lang_id'] = $postedData['lang_id'];
                    $customerData['com_id'] = $postedData['com_id'];
                    $customerData['cust_title'] = $postedData['cust_title'];
                    $customerData['cust_firstname'] = $postedData['cust_firstname'];
                    $customerData['cust_lastname'] = $postedData['cust_lastname'];
                    $customerData['cust_phone'] = $postedData['cust_phone'];
                    $customerData['cust_mobile_no'] = $postedData['cust_mobile_no'];
                    $customerData['cust_fax'] = $postedData['cust_fax'];
                    $customerData['cust_address'] = $postedData['cust_address'];
                    $customerData['cust_city'] = $postedData['cust_city'];
                    $customerData['cust_state'] = $postedData['cust_state'];
                    $customerData['cust_country'] = $postedData['cust_country'];
                    $customerData['cust_zipcode'] = $postedData['cust_zipcode'];
                    $customerData['cust_quality'] = $postedData['cust_quality'];
                    $customerData['cust_securityquestion'] = $postedData['cust_securityquestion'];
                    $customerData['cust_securityanswer'] = $postedData['cust_securityanswer'];
                    $customerData['cust_availability'] = $postedData['cust_availability'];

                    //   $customerData['cust_status'] = $postedData['cust_status'];
                    $customerData['cust_updateddate'] = date("Y-m-d H:i:s");

                    $Customerid =  $customerModel->save($customerData, 'cust_id');
                   
                    $department_customer['cust_id'] = $Customerid;
                    $department_customer['lgn_id'] = $lgn_id;
                    $department_customer['cust_dep_status'] = $postedData['cust_status'];
                    $department_customer['updated_lgn_id'] = $updated_userid;
                    $department_customer['cust_dep_createddate'] = date("Y-m-d H:i:s");
                    
                    //delete all department of customer
                    $departmentcustomerData = $departmentcustomerModel ->fetchDepartmentBycustomer($Customerid);
                    
                    foreach ($departmentcustomerData as $key => $_depp){
                         $departmentcustomerModel->deleteDepartmentcustomer($key);
                    }
                     
                    foreach ($postedData['dep_id'] as $value){
                        $department_customer['dep_id'] = $value;
                        $departmentcustomerModel->save($department_customer, 'con_dep_id');
                    }
                    
                    

                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("customer_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("customer_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'customer', '');
                }
            }
        }
        if ($this->USER->role == "CUSTOMER") {
            $this->view->customerid = $cust_id;
            $this->view->imageName = $imageName;
            $this->view->USER_ROLE = $this->USER->role;
            $this->view->errorMessageArray = $errorMessageArray;
            $this->view->succesMessage = $successmessage;
            $this->view->form = $customerForm;
        } else {
            $this->_helper->redirector('list', 'customer', '');
        }
    }
    
    
    public function departmentlistAction() {
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $customerModel =new Model_Customer();
            $com_id = $postedData['com_id'];
            $where = "site.com_id = '".$com_id."'";
            //Load the department array for the select box in form 
            $departmentArray = $customerModel->getdepartmentArray($where);
            $jsonString = "";
            foreach($departmentArray as $key => $_dep) {
                    //print_r($_cust);
                    $jsonString .= "<option value = '".$key ."'>".$_dep."</option>";
                }
        }
      echo $jsonString;
      exit;
    }
    
    public function  dashboardAction(){
        
        $requestData = array();
        $orderField = 'request.req_id';
        $sort = 'asc';
        $paginator = '';
        $where = '1=1 ';
        $this->view->frm_date = date('Y-m-d',strtotime(' -1 day'));
        $this->view->to_date = date('Y-m-d');
        
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }
        //$assignrequestModel = new Model_Assignrequest(); // load assignrequest model
        
        
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE
        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        
       

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

       //$where, $itemsPerPageReviews, $offset, $orderField, $sort
        
        $loggeduser = array();
        $loggeduser['roletype'] = $this->USER->roletype;
        $loggeduser['loggeduserid'] = $this->USER->usr_id;
       
        
            $requestModel = new Model_Request();
            $requestAssignmodel = new Model_Assignrequest();
            
             //search functionality
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            
            if($postedData["frm_date"] == ''){
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = '';
            }
            if($postedData["to_date"] == ''){
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = '';
            }
            if($postedData["dash_comment"] == ''){
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = '';
            }if($postedData["req_reference"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = '';
               // $this->view->req_ref = '';
            }if($postedData["site_id"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = '';
                //$this->view->site_id = '';
            }if($postedData["subj_id"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = '';
               // $this->view->subj_id = '';    
            }if($postedData["ass_status"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = '';
               // $this->view->ass_status = '';    
            }
            
            if (isset($postedData["dash_comment"]) && $postedData["dash_comment"]!= '' ) {
                $searchtype = $postedData["dash_comment"];
                $where .= " and req_comment LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = $searchtype;
                $this->view->dash_comment = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'];
            }
            if (isset($postedData["frm_date"]) && $postedData["frm_date"]!= '' && isset($postedData["to_date"])&&  $postedData["to_date"]!= '' ) {
                $frm_date = $postedData["frm_date"];
                $to_date = $postedData["to_date"];
                $where .= " and req_date BETWEEN '".$frm_date."' and '".$to_date."' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = $frm_date;
                $this->view->frm_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'];
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = $to_date;
                $this->view->to_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'];
            }
            if (isset($postedData["req_reference"]) && $postedData["req_reference"]!='' ) {
                $searchtype = $postedData["req_reference"];
                $where .= " and req_reference = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = $searchtype;
                $this->view->req_ref = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'];
            }
            if (isset($postedData["site_id"]) && $postedData["site_id"]!='' ) {
                $searchtype = $postedData["site_id"];
                $where .= " and request.site_id  = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = $searchtype;
                $this->view->site_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'];
            }
            if (isset($postedData["subj_id"]) && $postedData["subj_id"]!='' ) {
                $searchtype = $postedData["subj_id"];
                $where .= " and request.subj_id  = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = $searchtype;
                $this->view->subj_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'];
            }
            if (isset($postedData["ass_status"]) && $postedData["ass_status"]!='' ) {
                $searchtype = $postedData["ass_status"];
                $where .= " and ass_status  = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = $searchtype;
                $this->view->ass_status = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'];
            }

        } 
        else{
            $session_search = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
             if(isset($session_search["frm_date"]) && $session_search["frm_date"] == ''){
                $session_search["frm_date"] = date('Y-m-d',strtotime(' -1 day'));
            }
            
            if(isset($session_search["to_date"]) && $session_search["to_date"] == ''){
                $session_search["to_date"] = date('Y-m-d');
            }
            if (isset($session_search["dash_comment"]) && $session_search["dash_comment"]!= '' ) {
                $searchtype = $session_search["dash_comment"];
                $where .= " and req_comment LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = $searchtype;
                $this->view->dash_comment = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'];
            }
            if (isset($session_search["frm_date"]) && $session_search["frm_date"]!= '' && isset($session_search["to_date"])&&  $session_search["to_date"]!= '' ) {
                $frm_date = $session_search["frm_date"];
                $to_date = $session_search["to_date"];
                $where .= " and req_date BETWEEN '".$frm_date."' and '".$to_date."' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = $frm_date;
                $this->view->frm_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'];
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = $to_date;
                $this->view->to_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'];
            }
            if (isset($session_search["req_ref"]) && ($session_search["req_ref"] != "")) {
                $searchtype = $session_search["req_ref"];
                $where .= " and req_reference = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = $searchtype;
                $this->view->req_ref = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'];
            }
            if (isset($session_search["site_id"]) && ($session_search["site_id"] != "")) {
                $searchtype = $session_search["site_id"];
                $where .= " and request.site_id  = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = $searchtype;
                $this->view->site_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'];
            }
            if (isset($session_search["subj_id"]) && ($session_search["subj_id"] != "")) {
                $searchtype = $session_search["subj_id"];
                $where .= " and request.subj_id  = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = $searchtype;
                $this->view->subj_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'];
            }
            if (isset($session_search["ass_status"]) && ($session_search["ass_status"] != "")) {
                $searchtype = $session_search["ass_status"];
                $where .= " and ass_status  = '".$searchtype."'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = $searchtype;
                $this->view->ass_status = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'];
            }
            
        } 
      
        
            $where .= " and request.req_com_id = ".$this->USER->company_id;
            $requestData = $requestModel->fetchRequestWithassign($where);
           
            //search dropdown
        
            $searchrequestData = $requestModel->fetchRequestWithassign(' request.req_com_id = '.$this->USER->company_id.'',$itemsPerPageReviews, $offset, $orderField, $sort);
           
        
            $paginator = new GTL_Paginator();
            $paginator->setItemsPerPage($itemsPerPageReviews);
            $paginator->setItemsTotal($requestModel->getRequestWithassignCount($where));
            $paginator->setCurrentPage($currentPageReviews);
            $link = $this->view->url(array('controller' => 'customer', 'action' => 'dashboard', 'page' => 'PAGENO'), 'default', false);
            $paginator->paginate($link);
        
        
        $this->view->assignstatus = $requestAssignmodel->getStatusArray();
        $this->view->paginator = $paginator;
        $this->view->searchrequestData = $searchrequestData;
        $this->view->requestData = $requestData;
        
        
    }
    
    public function downloadpdfAction(){
    
        $requestModel = new Model_Request();
        $requestlogModel = new Model_Requestlog();
        $requestcommentModel = new Model_Requestcomment();
        $metaModel = new Model_Metadata();
        $metaData = $metaModel->fetchEntryByKey("HEADER_LOGO");
        $Header_Logo = $metaData['mtd_value'];
        
        $where = "1=1 ";
        
            $session_search = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            if (isset($session_search["dash_comment"]) && $session_search["dash_comment"]!= '' ) {
                $searchtype = $session_search["dash_comment"];
                $where .= " and req_comment LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = $searchtype;
                $this->view->dash_comment = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'];
            }
            if (isset($session_search["frm_date"]) && $session_search["frm_date"]!= '' && isset($session_search["to_date"])&&  $session_search["to_date"]!= '' ) {
                $frm_date = $session_search["frm_date"];
                $to_date = $session_search["to_date"];
                $where .= " and req_date BETWEEN '".$frm_date."' and '".$to_date."' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = $frm_date;
                $this->view->frm_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'];
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = $to_date;
                $this->view->to_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'];
            }
            if (isset($session_search["req_ref"]) && ($session_search["req_ref"] != "")) {
                $searchtype = $session_search["req_ref"];
                $where .= " and req_reference LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = $searchtype;
                $this->view->req_ref = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'];
            }
            if (isset($session_search["site_id"]) && ($session_search["site_id"] != "")) {
                $searchtype = $session_search["site_id"];
                $where .= " and request.site_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = $searchtype;
                $this->view->site_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'];
            }
            if (isset($session_search["subj_id"]) && ($session_search["subj_id"] != "")) {
                $searchtype = $session_search["subj_id"];
                $where .= " and request.subj_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = $searchtype;
                $this->view->subj_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'];
            }
            if (isset($session_search["ass_status"]) && ($session_search["ass_status"] != "")) {
                $searchtype = $session_search["ass_status"];
                $where .= " and ass_status LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = $searchtype;
                $this->view->ass_status = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'];
            }
            
            
        //$requestData = $requestModel->fetchRequestWithassign();
         
        $where .= " and request.req_com_id = ".$this->USER->company_id;
        $requestData = $requestModel->fetchRequestWithassign($where);
            
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->SetTitle('SERVICE-APP');

        // set default header data
        //$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);
       if($Header_Logo != ''){
           $image = $this->view->PUBLIC_PATH . "upload/logo/".$Header_Logo;
           $pdf->SetHeaderData($image, '', '', '');
       }else{
           $pdf->SetHeaderData('', '', PDF_HEADER_TITLE, '');
       }
       
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        $pdf->SetFont('dejavusans', '', 10);

        // add a page
        $pdf->AddPage();

        $html = '<h1>Request Detail</h1>';

        $pdf->writeHTML($html, true, false, true, false, '');
       
         

        foreach($requestData as $key =>$value){
           //$requestidData = $requestModel->fetchEntryByViewId($value['req_id']);
            $html = '
               <b>New  Request '.$value['req_reference'].'</b> <br/><br/>
        <table border="0" cellspacing="1" cellpadding="1">
            <tr>
                <th><b>Request Ref.</b></th>
                <th><b>Date</b></th>
                <th><b>Site Name</b></th>
                <th><b>Subject Name</b></th>
                <th><b>Added By</b></th>
                <th><b>Assign To</b></th>
                <th><b>Status</b></th>
                   </tr>';
         $req_hist = '<b>Request History:</b><br/><br/>
                        <table border="0" cellspacing="1" cellpadding="1">
                            <tr>
                                <th><b>Date</b></th>
                                <th><b>Assign By</b></th>
                                <th><b>Assign To</b></th>
                                <th><b>Status</b></th>
                           </tr>';
           
         //Status
                $status = '<span color="red">Pending</span>';
                if ($value['ass_status'] == 3){
                    $status = 'Done';
                }if ($value['ass_status'] == 4){
                    $status = 'Pending';
                }if ($value['ass_status'] == 5){
                    $status = 'In Progress';
                }if ($value['ass_status'] == 6){
                    $status = 'Assign';
                }if ($value['ass_status'] == 7){
                    $status = 'Seen';
                }
                
                if($value['cont_firstname'] != ''){
                    $ass_to = ucfirst($value['cont_firstname']." ".$value['cont_lastname'])." [Contractor]";
                }else if($value['cust_firstname'] != ''){
                    $ass_to = ucfirst($value['cust_firstname']." ".$value['cust_lastname'])." [Customer]";
                }else{
                    $ass_to = '<span color="red">Pending</span>';
                }
                
            $html .= ' <tr>
                        <td>'.$value['req_reference'].'</td>
                        <td>'.$value['req_date'].' '.date('h:i',strtotime($value['req_createddate'])).'</td>
                        <td>'.$value['site_name'].'</td>
                        <td>'.$value['subj_name'].'</td>
                        <td>'.ucfirst($value['com_name']).'</td>
                        <td>'.$ass_to.'</td>
                        <td>'.$status.'</td>
                    </tr>';
            
            
            //Request Log
            $where_log = "req_id = ".$value['req_id'];
            $requestlogData = $requestlogModel->fetchRequestlog($where_log);
            if(count($requestlogData) >0){
            foreach($requestlogData as $log_key => $log_value){
            //Ass By      
                if( $log_value['ass_by'] == 1){
                  $ass_by_name =  'Admin' . " ( ".ucfirst($log_value['update_adm_firstname']." ".$log_value['update_adm_lastname'])." )";  
                }
                if( $log_value['ass_by'] == 2 || $log_value['ass_by'] == 3){
                 $ass_by_name = 'Contractor'. " ( ".ucfirst($log_value['update_cont_firstname']." ".$log_value['update_cont_lastname'])." )";  
                }

                //Status
                if ($log_value['ass_type'] == 3){
                    $ass_type = 'Done';
                }if ($log_value['ass_type'] == 4){
                    $ass_type = 'Pending';
                }if ($log_value['ass_type'] == 5){
                    $ass_type = 'In Progress';
                }if ($log_value['ass_type'] == 6){
                    $ass_type = 'Assign';
                }if ($log_value['ass_type'] == 7){
                    $ass_type = 'Seen';
                }
            
                $req_hist .='<tr>
                    <td>'.date('Y-m-d H:i', strtotime($log_value['log_createddate'])).'</td>
                    <td>'.$ass_by_name.'</td>
                    <td>'.ucfirst($log_value['cont_firstname']." ".$log_value['cont_lastname']).'</td>
                    <td><span color="red">'.$ass_type.'</span></td>
                </tr>';
            }
            }
            else{
                 $req_hist .='<tr>
                    <td colspan="4">No Record Found</td></tr>';
            }
            
            
            $comment = '<h3>Comments</h3>';

           
            $html .= '</table>';
            $req_hist .= '</table>';
            $pdf->writeHTML($html, true, false, true, false, '');
            $pdf->writeHTML($req_hist, true, false, true, false, '');
            $pdf->writeHTML($comment, true, false, true, false, '');
            
            
            $requestCommentData = $requestcommentModel->fetchRequestComment($where_log);
            
            if(count($requestCommentData) >0){
                foreach($requestCommentData as $cmt_key => $cmt_value){
                    $leftcol =  '<b>'.ucfirst($cmt_value['Name']).' </b><span color="red"> '.$cmt_value['Addedby'].'</span>';
                    $rightcol = ''.date('Y-m-d H:i',  strtotime($cmt_value['createDate'])).'';
                    $y = $pdf->getY();
                    $pdf->SetFillColor(255, 255, 255);
            
                    $pdf->writeHTMLCell(150, '', '', $y, $leftcol, 0, 0, 1, true, 'J', true);
                    $pdf->writeHTMLCell(80, '', '', '', $rightcol, 0, 1, 1, true, 'J', true);
            
                    
                    $add_attch = '' ;
                    if ($cmt_value['cmnt_add_attachment'] != ''){
                        $add_attch = '<p>
                            <a target="_blank" href="'.$this->view->BASE_URL.'public/upload/comment_attachment/'.$cmt_value['cmnt_add_attachment'].'">View Attachment</a>
                                </p>';
                    }else{
                        $add_attch = '' ;
                    }                            
                                                
                    $comment_data ='<style>   
                        div.mainclass {
                            border-style: solid;
                            border-width: 1px;
                            border-color: #000;
                                    width : 100%;
                        }
                    </style>
                    <div>  '.$cmt_value['comment'].'</div>
                     '.$add_attch.'
                    <div class="mainclass"></div>';
                    
                    $pdf->writeHTML($comment_data, true, false, true, false, '');
                }
            }else{
                $comment_data = '<br/><br/>No Comment Found.';
                $pdf->writeHTML($comment_data, true, false, true, false, '');
            }
            
            
             if(count($requestData) != ($key+1)){
                $pdf->AddPage();
            }
          
                   
        }  
        
    $pdf->Output('Request.pdf', 'D');
       exit;     
    }
   

      public function managecustomerAction(){
        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $contractorData = Array();
        $company_where = '';
        $customer_where = '';
        //Load Contractor Model 
        $customerModel = new Model_Customer();
        //Load Contractor Form
        $customerForm = new Form_SupercustomerForm();
        
        //Load the Company array for the select box in form 
        $companyArray = $customerModel->getcompanyArray("com_type = 2");
        $customerForm->com_id->addMultiOptions($companyArray);
        
        //Load the Company array for the select box in form 
        $customerArray = $customerModel->getcustomerArray($this->USER->usr_lang_id);
        $customerForm->cust_id->addMultiOptions($customerArray);
        
         if ($this->getRequest()->isPost()) {
         //Check for Errors
            $postedData = $this->_request->getPost();
             if($postedData['com_id'] != ''){
                 $customerWhere = "cust.com_id = '" . $postedData['com_id'] . "'";
                 $customerArray = $customerModel->getcustomerArray($this->USER->usr_lang_id,$customerWhere);
                 $customerForm->cust_id->addMultiOptions($customerArray);
             }   
            
             if (!$customerForm->isValid($postedData)) {
                $errorMessage = $customerForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            }else{
                if (count($errorMessageArray) > 0) {

                } else {
                        $supercustomer_where = "cust_isadmin = 1";
                        $supercustomerArray = $customerModel->fetchCustomer($this->USER->usr_lang_id,$supercustomer_where);  
                        
                        $_SUPERDATA1['cust_id'] = $supercustomerArray[0]['cust_id'];
                        $_SUPERDATA1['cust_isadmin'] = 0;
                        $customerModel->save($_SUPERDATA1, 'cust_id');
                        
                        $_SUPERDATA['cust_id'] = $postedData['cust_id'];
                        $_SUPERDATA['cust_isadmin'] = 1;
                        $customerModel->save($_SUPERDATA, 'cust_id');
                        $this->_helper->redirector('list', 'customer', '');
                   
                    
                    
                }
            }
         }
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $customerForm;
    }
    
      public function customerlistAction(){
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $customerModel =new Model_Customer();
            $com_id = $postedData['com_id'];
            $customerWhere = "cust.com_id = '" . $com_id . "'";
            //Load the customer array for the select box in form 
            $customerArray = $customerModel->getcustomerArray($this->USER->usr_lang_id,$customerWhere);
            $jsonString = "";
            $jsonString ="<select name='cust_id' id='cust_id'>";
            foreach($customerArray as $key => $_cont) {
                    //print_r($_cont);
                    $jsonString .= "<option value = '".$key ."'>".$_cont."</option>";
                }
             $jsonString .= "</select>";
           
            
        }
      echo $jsonString;
      exit;
    } 

    
 public function deleterequestAction() {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $requestModel->deleteRequest($request_id);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_delete_success"));
        }
        $this->_helper->redirector('dashboard', 'customer', '');
    }

     public function acknowledgeAction() {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $data = array('req_acknowledge' => '1');
            $requestModel->update($data, 'req_id =' . (int) $request_id);
            
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_acknowledge_success"));
        }
         if ($this->USER->role == 'ADMIN') {
            $this->_helper->redirector('dashboard', 'admin', '');
        } else if ($this->USER->role == 'CUSTOMER') {
            $this->_helper->redirector('dashboard', 'customer', '');
        } else {
            $this->_helper->redirector('dashboard', 'contractor', '');
        }
    }
    
    public function closerequestAction() {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $data = array('req_closerequest' => '1','closed_datetime'=>date('Y-m-d H:i:s'));
            $requestModel->update($data, 'req_id =' . (int) $request_id);
            
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_closed_success"));
        }
         if ($this->USER->role == 'ADMIN') {
            $this->_helper->redirector('dashboard', 'admin', '');
        } else if ($this->USER->role == 'CUSTOMER') {
            $this->_helper->redirector('dashboard', 'customer', '');
        } else {
            $this->_helper->redirector('dashboard', 'contractor', '');
        }
    }
   

   

}

?>